from flask import Flask, jsonify, request,Blueprint,current_app,g
from flask_cors import CORS
from sqlalchemy import create_engine,text
import pandas as pd
import numpy as np
from datetime import datetime
from table import table
from curve import curve
from curveprint import curveprint
from translations import translations
import serverFiles
import sys,platform
# import db_keep_alive

def get_db_connection():
    data = serverFiles.dataSource
    engine_dict = {}
    for d in data['DataSourceArray']:
        # 从 JSON 文件中提取数据库连接参数
        db_params = d['DatabaseParam']
        db_type = 'mysql+pymysql'
        db_user = db_params['User']
        db_password = db_params['Password']
        db_host = db_params['Host']
        db_port = db_params['ServerPort']
        db_name = db_params['Name']
        
        if platform.system() == 'Windows':
            db_host = '172.16.14.99'

        # 使用 SQLAlchemy 的 create_engine() 方法创建数据库连接引擎
        engine = create_engine(f'{db_type}://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}')
        # print(engine)
        engine_dict[d['Name']] = engine
    return engine_dict
    # raise ValueError(f"连接数据库找不到数据源名 {dataSourceName}")

def get_db_connection_test():
    db_type = 'mysql+pymysql'
    db_user = 'root'
    db_password = '123'
    db_host = 'localhost'
    db_port = '3306'
    db_name = 'scada'
    engine = create_engine(f'{db_type}://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}')
    return engine


def create_app():
    app = Flask(__name__)
    CORS(app, resources={
    r"/*": {
        "origins": "*",
        "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        "allow_headers": ["Content-Type", "Authorization"]
    }
    })
    app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 最大接受 16MB 的数据 保存图片
   
    engine_dict = {}
    engine_dict = get_db_connection()    
    
    # 打印数据库连接信息
    data = serverFiles.dataSource
    print("\n数据库连接信息:")
    for d in data['DataSourceArray']:
        db_host = d['DatabaseParam']['Host']
        if platform.system() == 'Windows':
            db_host = '172.16.14.99'
        print(f"数据源: {d['Name']}, 主机: {db_host}")
    print()
    
    app.serverPath = serverFiles.serverPath
    app.engine_dict = engine_dict

    #注册蓝图
    app.register_blueprint(bp)
    app.register_blueprint(curveprint)
    app.register_blueprint(table)
    app.register_blueprint(curve)
    app.register_blueprint(translations)

    
    # db_keep_alive.start_keep_alive_task(app, engine_dict) # 保持mysdql不会超时
    
    return app

#测试的蓝图
bp = Blueprint('bp', __name__)
@bp.route('/')
def index():
    return 'Hello from bp'

@bp.route('/data1')
def data1():
    data = serverFiles.dataSource
    config_list = []
    for d in data['DataSourceArray']:
        # 从 JSON 文件中提取数据库连接参数
        db_params = d['DatabaseParam']
        db_type = 'mysql+pymysql'
        db_user = db_params['User']
        db_password = db_params['Password']
        db_host = db_params['Host']
        db_port = db_params['ServerPort']
        db_name = db_params['Name']

        # 使用 SQLAlchemy 的 create_engine() 方法创建数据库连接引擎
        v = (f'{db_type}://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}')
        config_list.append(d['Name'] + '  ' + v)
    return jsonify(config_list)


app = create_app()
if __name__ == '__main__':
    sys.argv
    now = datetime.now()
    print("启动时间 now =", now)
    app.run(host="0.0.0.0", port=5000)

# current date and time
now = datetime.now()
print("启动时间1 now =", now)